package com.bianxianmao.myinfo.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bianxianmao.R;
import com.bianxianmao.utils.Constants;
import com.bianxianmao.utils.Utils;
import com.loopj.android.http.AsyncHttpClient;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;
//找回密码


public class FindpasswordActivity extends Activity implements View.OnClickListener {
    /**
     * 客户端输入的验证码
     */
    private String identifycode;
    private TextView tvAlreadyRegist;
    private EditText etphone;
    private TextView useagreement;
    private Button getidentify;
    private MyCountDownTimer countDownTimerUtils;
    //密码的正则表达式
    private String reg;
    //手机号的正则表达式
    private String regex;
    private EditText etpwd;
    private EditText etgetidentify;
    private Button commit;
    private String phone;
    //发送验证码接口
    private String getcodeURL = "http://1.migree.com.cn/duobao/userLogin/sendSMSCode.json";
    //注册接口
    private String phoneregisterurl = "http://1.migree.com.cn/duobao/userLogin/phoneRegister.json";
    private AsyncHttpClient client = new AsyncHttpClient();
    //短信验证码内容 验证码是6位数字的格式
    private String strContent;
    private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_findpassword);
        initView();
    }

    //复写倒计时
    class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            getidentify.setClickable(false);
            getidentify.setTextColor(R.color.buttonColor_gray);
            getidentify.setText(l / 1000 + "s秒后重发");
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            getidentify.setText("重新获取验证码");
            //设置可点击
            getidentify.setClickable(true);
        }
    }

    private void initView() {
        etphone = (EditText) findViewById(R.id.et_phone);
        etpwd = (EditText) findViewById(R.id.et_password);
        etgetidentify = (EditText) findViewById(R.id.et_identifycode);
        getidentify = (Button) findViewById(R.id.btn_get_identifycode);
        commit = (Button) findViewById(R.id.btn_commit);
        getidentify.setOnClickListener(this);
        commit.setOnClickListener(this);
    }
//    //更新界面
//    private Handler mHandler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            if (etgetidentify != null) {
//                etgetidentify.setText(strContent);
//            }
//        }
//
//    };
//    //从服务器中接收验证码
//    public void getCode(){
//        HashMap<String, String> map = new HashMap<String, String>();
//        map.put("phone",  phone);
//        RequestParams params = new RequestParams(map);
//        client.post(getcodeURL, params, new JsonHttpResponseHandler(){
//            @Override
//            public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
//                Log.e("", response.toString());
//                super.onSuccess(statusCode, headers, response);
//                Toast.makeText(FindpasswordActivity.this, "短信已成功发送，请注意查收", 1).show();
//                try {
//                    String message=response.getString("code");
//                    //这个方法是正则表达式，但是因为我后台返回的是空，所以我这里正则表达式就暂时注释掉了，如果你后台是可以打印出验证码的这里你可以打开
//                    String code = patternCode(message);
//                    Log.i("AAA", "onSuccess: "+code);
//                    if (!TextUtils.isEmpty(message)) {
//                        strContent = message;
//                        mHandler.sendEmptyMessage(1);
//
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//
//            @Override
//            public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers,
//                                  String responseString, Throwable throwable) {
//                super.onFailure(statusCode, headers, responseString, throwable);
//            }
//
//            @Override
//            public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers,
//                                  Throwable throwable, JSONObject errorResponse) {
//                super.onFailure(statusCode, headers, throwable,
//                        errorResponse);
//            }
//        });
//    }

    /**
     * 匹配短信中间的6个数字（验证码等）
     *
     * @param patternContent
     * @return
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile(patternCoder);
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    @Override
    public void onClick(View v) {
        //获取手机号
        phone = etphone.getText().toString().toString().trim();
        //获取输入短信验证码
        identifycode = etgetidentify.getText().toString().trim();
        //获取输入密码
        String pwd = etpwd.getText().toString();
        boolean phoneresult = Utils.isPhone(phone);
        boolean pwdresult = Utils.isPhone(pwd);
        switch (v.getId()) {
            case R.id.btn_get_identifycode://获取验证码
                if (phone.isEmpty()) {
                    Toast.makeText(FindpasswordActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (phoneresult == false) {
                    Toast.makeText(FindpasswordActivity.this, "输入手机号码不正确", Toast.LENGTH_SHORT).show();
                    break;
                }
                new MyCountDownTimer(60000, 1000).start();
                String url = Constants.REGISTER + "?mobile=" + phone + "&type=2";
                StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i(TAG, "onResponse: ================" + response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                break;

            case R.id.btn_commit://提交
                if (phone.isEmpty()) {
                    Toast.makeText(FindpasswordActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (phoneresult == false) {
                    Toast.makeText(FindpasswordActivity.this, "输入手机号码不正确", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (identifycode.isEmpty()) {
                    Toast.makeText(FindpasswordActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (pwd.isEmpty()) {
                    Toast.makeText(FindpasswordActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (pwdresult == false) {
                    Toast.makeText(FindpasswordActivity.this, "请6-16位密码", Toast.LENGTH_SHORT).show();
                    break;
                }
                new StringRequest(Request.Method.GET, Constants.FINDPASSWORDURL + "?mobile=" + phone + "&passWord=" + pwd + "smsCode=" + identifycode, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("ABC", "onResponse: " + response);

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                Toast.makeText(FindpasswordActivity.this, "恭喜您提交成功", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(FindpasswordActivity.this, SuccessregisterActivity.class));
        }
    }
}
